package com.rx.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.rx.common.DBUtils;
import com.rx.entity.Logs;
import com.rx.entity.Role;

public class LogsDaoImpl implements LogsDaoI<Logs> {

	@Override
	public boolean insert(Logs logs) throws SQLException {
		Connection conn = DBUtils.getConnection();
		String sql = "INSERT INTO  logs (operateType,content,operateDate) VALUES(?,?,?)";
		// 创建PreparedStatement
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setInt(1, logs.getOperateType());
		ps.setString(2, logs.getContent());
		//添加当前日期
		ps.setDate(3, new Date(new java.util.Date().getTime()));
		// 执行语句
		if (ps.executeUpdate() > 0) {
			return true;
		}
		DBUtils.close(conn, ps, null);
		return false;
	}

	@Override
	public List<Logs> selectAll() {
		return null;
	}

	@Override
	public boolean delete(int id) {
		return false;
	}

	@Override
	public boolean update(Logs t) throws Exception {
		return false;
	}

	@Override
	public List<Logs> selectWhere(String whereSql) throws Exception {
		return null;
	}

	@Override
	public Map<String, Object> selectPage(String whereSql, int currentPage, int pageSize) throws Exception {
		Connection conn = DBUtils.getConnection();
		int index = (currentPage - 1) * pageSize;
		String sql = "SELECT id,operateType,content,operateDate FROM logs WHERE 1=1 " + whereSql + "ORDER BY id desc LIMIT " + index + "," + pageSize;
		PreparedStatement ps0 = conn.prepareStatement(sql);
		ResultSet rs0 = ps0.executeQuery();
		List<Logs> list = new ArrayList<>();
		while (rs0.next()) {
			Logs logs = new Logs();
			logs.setId(rs0.getInt(1));
			logs.setOperateType(rs0.getInt(2));
			logs.setContent(rs0.getString(3));
			logs.setOperateDate(rs0.getTimestamp(4));
			list.add(logs);
		}

		sql = "SELECT count(*) FROM logs  WHERE 1=1 " + whereSql;
		PreparedStatement ps1 = conn.prepareStatement(sql);
		ResultSet rs1 = ps1.executeQuery();
		int count = 0;
		int pageNum=0;
		if (rs1.next()) {
			count = rs1.getInt(1);
		}
		
		Map<String,Object> map=new HashMap<>();
		
		if(count%pageSize==0) {
			pageNum=count/pageSize;
		}else {
			pageNum=count/pageSize+1;
		}
		
		map.put("list", list);
		map.put("count", count);
		map.put("pageNum", pageNum);
		//关闭连接
		DBUtils.close(conn, ps0, rs0);
		DBUtils.close(conn, ps1, rs1);
		return map;
	}
}
